#!/bin/bash
####################################################################
# Prey Core Basic Functions - by Tomas Pollak (bootlog.org)
# URL: http://preyproject.com
# License: GPLv3
####################################################################

log(){
	eval echo -e '"$1"' "$log_output"
}

####################################################################
# xml parsing functions
####################################################################

get_key(){
	echo "$1" | sed -e 's/.*\/\(.*\)>/\1/' -e 'y/-/_/' # we also replace -'s to _'s
}

get_value(){
	echo "$1" | sed 's/.*>\([^<].*\)<.*/\1/'
}

# expects attr name, returns value
# example: get_attribute 'name' $line
get_attribute(){
	echo "$2" | sed "s/.*$1=\"\([^\"]*\)\".*/\1/"
	# echo "$2" | sed -e "s/.*$1=\([a-z_\"']*\).*/\1/" -e "s/[^a-z_]//g"
}

####################################################################
# setting configs
####################################################################

# key, value
set_config(){
	if [ -n "$2" ]; then
		# filter $() or backticks to prevent unwanted command execution
		local clean_val=$(echo "$2" | sed "s/[\`|\$(].*[\`|)]//g")
		eval "${1}=\"$clean_val\""
	fi
}

# module, key, value
set_module_config(){
	set_config "${1}__${2}" "$3"
}

save_config_value(){
	local key="$1"
	local val="$2"

	if [ "$val" == "true" ]; then
		local val='y'
	elif [ "$val" == 'false' ]; then
		local val='n'
	fi

    cp "$config_file" "$config_file.backup"
	sed -i -e "s/^$key=.*/$key='$val'/" "$config_file" 2> /dev/null
	local rs=$?
	if [ -f "$config_file" ]; then
		rm -f "$config_file.backup" 2> /dev/null
	else
		mv "$config_file.backup" "$config_file" 2> /dev/null
	fi

	return $rs
}

####################################################################
# local var storage
####################################################################

# fetches a var and then assigns it as $value
# expects the name of hash and then the name of var
get_var(){
	HASH="$1[*]"
	local ${!HASH}
	eval 'echo ${'"${2}"'}'
}

# if you need to fetch a specific trace or file
get_trace(){
	get_var traces ${1}__$2
}

get_file(){
	get_var files ${1}__$2
}

####################################################################
# trace functions
####################################################################

add_trace(){
	local urlencoded=`urlencode "$2"`
	local trace="${current_module}__$1=$urlencoded"
	log " ++ Adding trace for $current_module: $1"
	# we need to encode whitespaces, otherwise well get into trouble
	traces[${#traces[*]}]="$trace"
}

separator='########################################################'

list_traces(){
	# echo " -- ${#traces[*]} traces gathered!"
	for t in "${traces[@]}"
	do
		if [ "$post_method" == 'http' ]; then
			# echo -n $t | sed 's/^\([^_].*\)__\([^=].*\)=\(.*\)/\1[\2]="\3"\&/' # query string
			# echo "-F $t" | sed 's/^\([^_].*\)__\([^=].*\)=\(.*\)/\1[\2]=\3/' # form field list
			# echo $t | sed 's/^\([^_].*\)__\([^=].*\)=\(.*\)$/<\2>\3<\/\2>/' # xml
			local start=`echo ${t%%=*}`
			local index=`echo $(( ${#start} + 1 ))`
			local trace_field=`echo "-F $start" | sed 's/^\([^_].*\)__\(.*\)/\1[\2]/'`
			echo "${trace_field}=${t:index}"
		else
			local current_node=`echo $t | sed 's/__.*//'`
			if [ "$current_node" != "$previous_node" ]; then
				echo -e "$separator\n# $current_node\n$separator\n"
			fi
			# removes module name and replaces _'s with whitespaces
			echo -e "$t\n" | sed -e 's/^\([^_].*\)__/ :: /' -e 's/%20/ /g' -e 's/_/ /'
			local previous_node=$current_node
		fi
	done
}

remove_traces(){
	unset -v traces
	log " -- Dropping all traces!"
}


add_file(){
	if [ -f "$2" ]; then
		log " ++ Adding file for $current_module: $1 -> $2"
		files[${#files[*]}]=${current_module}__$1=$2
	else
		log " ${red}!!${color_end} Couldn't find file at $2!"
	fi
}

list_files(){
	# log " -- ${#files[*]} files gathered!"
	for f in "${files[@]}"
	do
		if [ "$post_method" == 'http' ]; then
			# echo -e "-F $f" | sed -e 's/=/=@/'
			echo "-F $f" | sed 's/^\([^_].*\)__\([^=].*\)=\(.*\)/\1[\2]=@\3/'
		else # just list the file paths
			echo $f | sed 's/^.*=\(.*\)/\1/'
		fi
	done
}

remove_files(){
	for f in "${files[@]}"
	do
		file=`echo $f | sed 's/^.*=\(.*\)/\1/'`
		rm -f "$file"
		log " -- Removed $file"
	done
	unset -v files
}

####################################################################
# delay functions, mac and linux
####################################################################

get_current_delay(){
	# crontab -l | grep prey | sed "s/^..\([0-9]*\).*/\1/"
	#/opt/cron/bin/crontab -l | grep prey | head -1 | sed 's/ [a\/].*//'
    cat /etc/init/apps/preyd.conf | grep preyd | cut -d ' ' -f 3
}

get_delay_for(){
	local delay_var=$(($1*1))
	if [ "$delay_var" == "$1" ]; then # integer, minute
		echo '*/'$1' * * * *'
	else
		case "$1" in
		"hourly")
			echo '1 * * * *' # first minute of every hour
			;;
		"daily")
			echo '1 10 * * *' # at 10:01 o'clock every day
			;;
		"weekly")
			echo '1 10 * * 1' # at 10:01 o'clock every monday
			;;
		# "monthly")
		# 	echo '1 10 1 * *' # at 10:01 o'clock every 1st of month
		# 	;;
		esac
	fi
}

update_execution_delay(){
	#local full_path=`full_path "$base_path"`
	#(/opt/cron/bin/crontab -l | tail -n+4 | grep -v prey; echo "${new_delay}" "aegis-exec -s ${full_path}/prey.sh > /var/log/prey.log") | /opt/cron/bin/crontab -
    initctl stop apps/preyd
    sed -i -e "s/preyd [0-9]*/preyd ${delay}/g" -e "s/every [0-9]*/every ${delay}/g" /etc/init/apps/preyd.conf
    initctl start apps/preyd
}

####################################################################
# http functions
####################################################################

send_request(){
	local curl_arguments="$2"
	local headers_file="$tmpbase/prey-curl-headers.txt"
	response_body=$(getter $curl_arguments -L $1 --dump-header "$headers_file")
	response_headers=$(cat "$headers_file" && rm -f "$headers_file" 2> /dev/null)
	get_status_code
}

get_status_code(){
	# if we get a redirect response, we should capture the last http status code
	response_status=`echo -e "$response_headers" | grep 'HTTP/' | tail -1 | cut -d" " -f2`
}

# we may eventually use a specific header for Prey
get_header_value(){
	echo "$response_headers" | grep "$1" | tail -1 | sed 's/.*: \([a-z\/-]*\).*/\1/'
}

# fetches last response if online actions were enabled for the device
get_last_response(){
	response_body=$(cat "$last_response")
}


####################################################################
# network core functions
####################################################################

get_internal_ip() {
	if [ -z "$internal_ip" ]; then
		internal_ip=`/sbin/ifconfig 2> /dev/null | grep "inet" | grep -v "inet6" | grep -v "127.0.0.1" | awk '{print $2}' | sed "s/[^0-9\.]//g" | head -1`
	fi
}

####################################################################
# check mode functions
####################################################################

verify_installation(){
	log " -- Checking if cron daemon is running..."
	if [ -n `is_process_running 'cron'` ]; then
		log " -- Cron daemon found."
	else
		log " !! Cron daemon not found! Try running it with 'sudo /etc/init.d/cron start'."
	fi
	log " -- Checking for crontab entry..."
	local result=`/opt/cron/bin/crontab -l | grep 'prey.sh' | wc -l 2> /dev/null`
	if [ "$result" -gt 0 ]; then
		log " -- Found!"
	else
		log " !! Not found!\n -> It seems Prey's crontab entry was removed after installation. Please set again the running interval."
	fi
}

verify_smtp_settings(){

	if [ "$mail_to" != "mailbox@domain.com" ]; then
		log " -- Target mailbox set."
	else
		log " !! Target mailbox not set!"
	fi

	if [ "$smtp_username" != "username@gmail.com" ]; then
		log " -- SMTP username set."
	else
		log " -- SMTP password not set!"
	fi

	if [ "$(decrypt \"$smtp_password\")" != "" ]; then
		log " -- Password seems to be fine as well."
	else
		log " -- Password not set! (Remember it should be base64 encrypted)."
	fi

}

####################################################################
# self setup functions
####################################################################

self_setup(){

	log ' -- Gathering PC info...'
	get_pc_info

	log ' -- Sending request to Control Panel...'
	local params="device[title]=$pc_name&device[device_type]=$pc_type&device[os_version]=$pc_os_version&device[os]=$(capitalize $os)"
	send_request "$check_url/devices.xml" "--connect-timeout 10 -u $api_key:x -d "$params""

	if [ $response_status == "201" ]; then

		log ' -- Device succesfully added! Applying configuration...'
		device_key=`echo "$response_body" | grep "<key>" | sed 's/.*<key>\(.*\)<\/key>.*/\1/'`

		save_config_value device_key "$device_key"

		if [ $? == 1 ]; then
			log " -- There was a problem saving the configuration. You probably don't have permissions to modify $base_path/config."
		else
			log " -- All set. Assigned key is $device_key."
		fi

	else

		log " -- Couldn't add this device to your account. Make sure you have available slots!\n"
		exit 1

	fi

}

####################################################################
# reverse ssh tunnel
####################################################################

open_reverse_tunnel(){

	local local_tunnel_port="$1"

	if [ -z "$remote_tunnel_port" ]; then
		log " -- Unknown remote port to connect to. Please try again later."
		return 1
	fi

	if [ ! -f "$tmpbase/prey-tunnel-${local_tunnel_port}.pid" ]; then
		log " -- Opening reverse tunnel from ${local_tunnel_port} to ${remote_tunnel_port} as ${remote_tunnel_user} on ${remote_tunnel_host}..."
		reverse_tunnel_command
		if [ -f "prey-tunnel.pid" ]; then
			mv "prey-tunnel.pid" "$tmpbase/prey-tunnel-${local_tunnel_port}.pid"
			log " -- Tunnel open and ready to serve!"
			update_device_info_with "device[active_tunnel]=${remote_tunnel_host}:${remote_tunnel_port}"
			return 0
		else
			log " -- Couldn't open reverse tunnel!"
			return 1
		fi
	else
		echo " -- Reverse tunnel already on!"
		return 0
	fi
}

close_reverse_tunnel(){
	local tunnel_pidfile="$tmpbase/prey-tunnel-${1}.pid"
	if [ -f "${tunnel_pidfile}" ]; then
		local tunnel_pid=`cat "$tunnel_pidfile"`
		log " -- Closing reverse tunnel on port ${1} with PID ${tunnel_pid}..."
		kill -9 $tunnel_pid &> /dev/null
		if [ $? == 1 ]; then
			log " -- Seems like the reverse tunnel was already closed!"
		fi
		rm -f "$tunnel_pidfile"
	fi
}
